package edu.suda.LoopCodePlus.service.impl;

import edu.suda.LoopCodePlus.entity.Solution;
import edu.suda.LoopCodePlus.mapper.SolutionMapper;
import edu.suda.LoopCodePlus.service.SolutionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SolutionServiceImpl implements SolutionService {
    @Autowired
    SolutionMapper solutionMapper;
    @Override
    public List<Solution> findAllSolution(Integer problemId) {
        List<Solution> solutions = null;
        try{
            solutions=solutionMapper.select_solutionByProblemId(problemId);
            return solutions;
        }catch (Exception e){
            return solutions;
        }
    }

    @Override
    public boolean insertSolution(Solution solution){
        try{
            solutionMapper.insert_solution(solution);
            return true;
        }catch (Exception e){
            System.out.println(e.getMessage());
            return false;
        }
    }
    @Override
    public Integer updateSolution(Integer userId, Integer solutionId ,Solution solution){
        try{
            Solution s =solutionMapper.select_solutionById(solutionId);
            if(s==null){
                return 1;  //改该题解不存在
            }
            else if(s.getUserId()==null|| !s.getUserId().equals(userId)){
                return 2;   //用户权限不足
            }
            solutionMapper.update_solutionById(solutionId,userId,solution);
            return 0;  //修改成功
        }catch (Exception e){
            return 3;   //数据库错误
        }
    }

    @Override
    public Integer deleteSolution(Integer solutionId, Integer userId) {
        try{
            Solution s =solutionMapper.select_solutionById(solutionId);
            if(s==null){
                return 1;  //该题解不存在
            }
            else if(s.getUserId()==null|| !s.getUserId().equals(userId)){
                return 2;   //用户权限不足
            }
            solutionMapper.delete_solutionById(solutionId,userId);
            return 0; //删除成功
        }catch (Exception e){
            return 3;
        }
    }

    @Override
    public Solution findSolutionById(Integer solutionId) {
        Solution solution = null;
        try{
            solution = solutionMapper.select_solutionById(solutionId);
            return solution;
        }catch (Exception e){
            return solution;
        }
    }
}
